package com.hefei.blog.base.utils.image.thread;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.image.ImageHandleUtils;

public class ImageScaleThread implements Runnable{

	private static Logger logger = Logger.getLogger(ImageScaleThread.class);
	
	private File ori;
	private String widthHeights;
	
	/**
	 * 存储在原文件相同的目录，只是修改文件名，加后缀
	 * @param ori 原图片
	 * @param width_heights 500_400,400_400,500_x,x_400
	 */
	public ImageScaleThread(File ori,String width_heights){
		this.ori = ori;
		this.widthHeights = width_heights;
	}
	
	/**
	 * 存储在原文件相同的目录，只是修改文件名，加后缀
	 * @param ori 原图片的绝对路径
	 * @param width_heights 500_400,400_400,500_x,x_400
	 */
	public ImageScaleThread(String oriFile,String width_heights){
		this(new File(oriFile), width_heights);
	}
	
	@Override
	public void run() {
		scale();
	}
	
	public void scale(){
		if(StringUtils.isNotEmpty(widthHeights) && ori != null){
			try{
				String[] widthHeightArr = widthHeights.split(",");
				String width = "";
				String height = "";
				String oriPathAndName = ori.getCanonicalPath();
				String destPathAdnName = null;
				for(String widthHeight : widthHeightArr){
					String[] wh = widthHeight.split("_");
					if(wh.length == 2){
						width = wh[0];
						height = wh[1];
						destPathAdnName = FileNameUtils.getFilename(oriPathAndName, width, height);
						
						if(widthHeight.startsWith("x")){//x_500
							ImageHandleUtils.scaleImage(oriPathAndName, destPathAdnName,Integer.valueOf(height).intValue());
						}else if(widthHeight.endsWith("x")){//400_x
							ImageHandleUtils.scaleImageByWidth(oriPathAndName, destPathAdnName, Integer.valueOf(width).intValue());
						}else{
							ImageHandleUtils.scale(oriPathAndName,destPathAdnName, Integer.valueOf(width).intValue(), Integer.valueOf(height).intValue());
						}
					}
				}
			}catch(Exception e){
				try {
					logger.error(" error " + ori.getCanonicalPath() + "  "+ widthHeights, e);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args){
		ImageScaleThread th = new ImageScaleThread(new File("D:\\liya\\23.jpg"), "100_400,400_x,x_500");
		th.run();
	}
	
	public File getOri() {
		return ori;
	}

	public void setOri(File ori) {
		this.ori = ori;
	}

	public String getWidthHeights() {
		return widthHeights;
	}

	public void setWidthHeights(String widthHeights) {
		this.widthHeights = widthHeights;
	}

}
